package com.kele.auth.service.impl;

import com.kele.auth.feign.UserFeignClient;
import com.kele.auth.model.dto.AuthParam;
import com.kele.auth.model.dto.UserExt;
import com.kele.auth.service.AuthService;
import com.kele.auth.util.SecurityUtil;
import com.kele.base.common.exception.AppException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2023/4/22 20:08
 * @Version:
 */
@Service("password_authService")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UserExt execute(AuthParam param) {

//        // 验证码
//        String checkCode = param.getCheckCode();
//        // 验证码的key
//        String checkCodeKey = param.getCheckCodeKey();
//
//        if (StringUtil.isEmpty(checkCode) || StringUtil.isEmpty(checkCodeKey)){
//            // 验证码为空
//            AppException.cast("请输入验证码");
//        }

        // 通过feign 获取用户信息
        SecurityUtil.User user = userFeignClient.getUserByUsername(param.getUsername());
        // 没有该用户的用户信息
        if (user == null){
            AppException.cast("账号不存在");
        }

        // 验证密码是否正确
        String passwordForm = param.getPassword();
        String passwordDb = user.getPassword();

        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches){
            AppException.cast("账号或密码错误");
        }

        UserExt userExt = new UserExt();
        BeanUtils.copyProperties(user, userExt);

        return userExt;
    }
}
